gesture = {}

-- min distance for detect a swipe
gesture.minSwipeDistance = 20
-- gesture duration
gesture.time = 0

function gesture.update (dt)
    if love.mouse.isDown(1) then
        local mouseX, mouseY = love.mouse.getPosition()
        if gesture.time == 0 then
            gesture.mouseX0, gesture.mouseY0 = mouseX, mouseY
        else
            gesture.mouseX1, gesture.mouseY1 = mouseX, mouseY
            if 
                gesture._getDistance(gesture.mouseX0, gesture.mouseY0, mouseX, mouseY) > 
                gesture.minSwipeDistance 
            then
                gesture.swiping = true 
            end

        end
        gesture.time = gesture.time + dt
    else
        if gesture.touching or gesture.swiping then
            if gesture.swiping then gesture._updateSpeed() end
            gesture.resetGesture()
        end
        if gesture.time > 0 and not gesture.swiping then
            gesture.touching = true
        end
    end

    if gesture.swiping and gesture.onSwipe then
        local x, y = gesture.getOrigin()
        gesture.onSwipe(x, y, gesture.getOffset())
    end 

    if gesture.touching and gesture.onTouch then
        gesture.onTouch(gesture.getOrigin())
    end
end

-- return swipe status
function gesture.isSwiping ()
    if not gesture.swiping then return end
    local x, y = gesture.getOrigin()
    return x, y, gesture.getOffset()
end

-- return speed of a swipe gesture
function gesture.getSpeed ()
    return  gesture._speed
end

-- update gesture speed with last gesture data
function gesture._updateSpeed ()
    gesture._speed = 
        gesture._getDistance(gesture.mouseX0, gesture.mouseY0, gesture.mouseX1, gesture.mouseY1)
        /gesture.time

    if gesture.mouseX0 > gesture.mouseX1 then
        gesture._speed = gesture._speed *-1
    end
end

-- return touch status
function gesture.isTouching ()
    if not gesture.touching then return end
    return gesture.getOrigin()
end

-- get the difference between the origin of a gesture and his last position
function gesture.getOffset ()
    if gesture.swiping then
        return  gesture.mouseX1 - gesture.mouseX0, gesture.mouseY1 + gesture.mouseY0
    end
end

-- reset gesture table state 
function gesture.resetGesture ()
        gesture.touching = false
        gesture.swiping  = false
        gesture.mouseX0  = nil
        gesture.mouseY0  = nil
        gesture.mouseX1  = nil
        gesture.mouseY1  = nil
        gesture.time     = 0
end

-- get the origin coordinate of gesture
function gesture.getOrigin ()
    return gesture.mouseX0, gesture.mouseY0 
end

-- get distance between two points
function gesture._getDistance (x0, y0, x1, y1)
    return math.sqrt((x1-x0)^2+(y1-y0)^2) 
end
